package epam.car.rent.web.tags;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;

import dataAccess.DbWriter;

import java.io.IOException;

/**
 * Custom tag that outputs reqired panels depending on session attribute
 * @author Alexander Tretyak
 *
 */
public class LoadPanels extends TagSupport {

    private static final Logger log = Logger.getLogger("carrentlogger");

	@Override
    public int doStartTag() throws JspException {
    	HttpSession session = (HttpSession) pageContext.getSession();
    	JspWriter w = pageContext.getOut();
    	
    	String currUser = null;
      	
    	int flag = 0; // 1 - client; 2 - admin;
    	
    	//String notloggedin = "$(\"#register\").hide(); $(\"#remind\").hide(); $(\"#currInfo\").hide();	$(\"#login input:first\").focus();";
     	//String loggedin = "$(\"#register\").hide(); $(\"#remind\").hide(); $(\"#login\").hide();	$(\"#currInfo\").fadeIn();";
    	String output = null;
    	if (session.getAttribute("clientID")!=null){
    		try{
    		currUser = DbWriter.getClientById((String)session.getAttribute("clientID")).getName();
    		flag = 1;
    		}catch(NullPointerException e){
    			// anyone is logged in
    		}
    		//currUser = (String)session.getAttribute("clientID");
    	}else {
    		try{
    		currUser = DbWriter.getManagerById((String)session.getAttribute("adminID")).getName();
    		flag = 2;
    		}catch(NullPointerException e){
    			// anyone is logged in
    		}
    	}
    	if(currUser!=null){
    		output = "$(\"#register\").hide(); $(\"#remind\").hide(); $(\"#login\").hide();	$(\"#currInfo\").fadeIn();";
    	}else{
    		output = "$(\"#register\").hide(); $(\"#remind\").hide(); $(\"#currInfo\").hide();	$(\"#login input:first\").focus();";
    	}
    	try {
			w.write("<script>");
			w.write("$(document).ready(function(){");
			w.write(output);
			w.write("$(\"#avalcars tr:even\").css(\"background-color\", \"#ffffff\")");
			w.write("});</script>");
		} catch (IOException e) {
			log.warn(e.getMessage());
		}
    	return SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }
}
